package com.yww.datastructure.queue;

import java.util.Iterator;

/**
 * @author yww
 * @description 环形数组实现队列(head, tail循环走法)
 * @since 2024/2/4 14:50
 */
public class ArrayQueue1<E> implements Queue<E> {
    private final E[] array;
    private int head;
    private int tail;
    private final int capacity;
    private int size = 0;

    public ArrayQueue1() {
        this(10);
    }

    public ArrayQueue1(int capacity) {
        // 环形数组预留一个位置，给判满使用
        this.capacity = capacity + 1;
        this.array = (E[]) new Object[this.capacity];
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        array[tail] = value;
        // 尾后移
        tail = (tail + 1) % capacity;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E val = array[head];
        array[head] = null; // help gc
        // 头后移
        head = (head + 1) % capacity;
        size--;
        return val;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        E val = array[head];
        return val;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return (tail + 1) % capacity == head;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;

            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E val = array[p];
                p = (p + 1) % capacity;
                return val;
            }
        };
    }
}
